package com.example.kingdee.jstSync.impl;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSONObject;
import com.example.kingdee.KingdeeCreate.impl.CreateSalBillImpl;
import com.example.kingdee.block.JuShuiTanBlock;
import com.example.kingdee.common.UUIDUtils;
import com.example.kingdee.config.RuoYiConfig;
import com.example.kingdee.dto.PurchaseSyncDto;
import com.example.kingdee.dto.SyncDto;
import com.example.kingdee.entity.*;
import com.example.kingdee.jstSync.JstSyncAbstract;
import com.example.kingdee.jstSync.entity.JstResult;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import com.example.kingdee.util.JuShuiTanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 云星空销售订单上传实现类
 */
@Service
public class JstSalOrderUploadImpl extends JstSyncAbstract {

    @Autowired
    private JuShuiTanBlock juShuiTanBlock;
    @Autowired
    private CreateSalBillImpl createSalBill;
    @Autowired
    private TBxStMapper tBxStMapper;
    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Override
    public int getOrderInfoPage(SyncDto syncDto, PurchaseSyncDto purchaseSyncDtoPage) {
        return JuShuiTanUtil.getOrderInfoPage(purchaseSyncDtoPage, FormIdEnum.purchaseQuery, juShuiTanBlock.getAccessToken());
    }

    @Override
    public JstResult selectJstResult(SyncDto syncDto, PurchaseSyncDto purchaseSyncDto) {
        JstResult jstResult = new JstResult();
        //查询销售订单明细信息
        List<Map<String, Object>> salOrderInfo = tBxStMapper.getSalOrderInfo(syncDto.getOrderId());
        //构建订单数据
        if (salOrderInfo != null && salOrderInfo.size() != 0){
            //查询表头信息
            Map<String, Object> salOrderBtInfo = tBxStMapper.getSalOrderBtInfo(syncDto.getOrderId());
            List<JstSalOrderUpload> jstAppointMenTinList = new ArrayList<>();
            JstSalOrderUpload jstSalOrderUpload = new JstSalOrderUpload();
            //处理表头信息
            jstSalOrderUpload.setKingdeeBillNo(salOrderBtInfo.get("billNo").toString());//金蝶单号
            jstSalOrderUpload.setShopNumber(Integer.parseInt(salOrderBtInfo.get("shopNumber").toString()));//店铺编码
            jstSalOrderUpload.setShopBuyerId(salOrderBtInfo.get("customerNumber").toString());//买家帐号
            jstSalOrderUpload.setReceiverAddress(salOrderBtInfo.get("receiverAddress").toString());//收货地址
            jstSalOrderUpload.setReceiverName(salOrderBtInfo.get("receiverName").toString());//收件人
            jstSalOrderUpload.setFreight(Double.parseDouble(salOrderBtInfo.get("freight").toString()));//运费
            jstSalOrderUpload.setReceiverState(salOrderBtInfo.get("receiverState").toString());//省
            jstSalOrderUpload.setReceiverCity(salOrderBtInfo.get("receiverCity").toString());//市
            jstSalOrderUpload.setReceiverDistrict(salOrderBtInfo.get("receiverDistrict").toString());//区
            jstSalOrderUpload.setReceiverPhone(salOrderBtInfo.get("phone").toString());//电话
            jstSalOrderUpload.setReceiverMobile(salOrderBtInfo.get("mobilePhone").toString());//手机
            jstSalOrderUpload.setLogisticsCompany(salOrderBtInfo.get("companyNumber").toString());//快递公司名称
            //处理物料信息
            List<ItemsItem> items = new ArrayList<>();
            double allMoney = 0.0;
            for (Map<String, Object> salOrder : salOrderInfo) {
                double fAmount = Double.parseDouble(salOrder.get("FAmount").toString());
                double fqty = Double.parseDouble(salOrder.get("FQTY").toString());
                allMoney = NumberUtil.add(allMoney, fAmount);
                ItemsItem item = new ItemsItem();
                item.setSkuId(salOrder.get("itemNumber").toString());
                item.setSalOrderInt((int)fqty);
                item.setRowMoney(fAmount);
                item.setPrice(salOrder.get("taxPrice"));
                item.setName(salOrder.get("itemName").toString());
                items.add(item);
            }
            jstSalOrderUpload.setPayAmount(allMoney);
            jstSalOrderUpload.setItemList(items);
            //处理支付信息
            JstSalOrderUpload.PayInfo payInfo = new JstSalOrderUpload.PayInfo();
            payInfo.setOuterPayId(salOrderBtInfo.get("payNumber").toString());//外部支付单号
            payInfo.setPayDate(salOrderBtInfo.get("payDate").toString());//支付日期
            payInfo.setPayment(salOrderBtInfo.get("payWay").toString());//支付方式
            payInfo.setSellerAccount(salOrderBtInfo.get("payAccountNumber").toString());//收款账号
            payInfo.setBuyerAccount(salOrderBtInfo.get("payMoneyNumber").toString());//支付账号
//            payInfo.setAmount(Double.parseDouble(salOrderBtInfo.get("payMoney").toString()));//支付总额
            payInfo.setAmount(NumberUtil.add(Double.parseDouble(salOrderBtInfo.get("freight").toString()), allMoney));//支付总额
            jstSalOrderUpload.setPay(payInfo);
            jstAppointMenTinList.add(jstSalOrderUpload);
            jstResult.setJstSalOrderUploadList(jstAppointMenTinList);
        }
        return jstResult;
    }

    @Override
    public void kingdeeSync(SyncDto syncDto, JstResult jstResult) {
        List<JstSalOrderUpload> jstSalOrderUploadList = jstResult.getJstSalOrderUploadList();
        //普通商品集合
        for (JstSalOrderUpload jstSalOrderUpload : jstSalOrderUploadList) {
            List<ItemsItem> itemList = jstSalOrderUpload.getItemList();
            ArrayList<HashMap<String, Object>> items = new ArrayList<>();
            for (ItemsItem item : itemList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("sku_id", item.getSkuId());//商品编码
                map.put("shop_sku_id", item.getSkuId());//店铺商品编码
                map.put("qty", item.getSalOrderInt());
                map.put("amount", item.getRowMoney());//成交总额（元）
                map.put("base_price", item.getPrice());//原价（元）
                map.put("name", item.getName());//商品名称长度<=100（元）
                map.put("outer_oi_id", UUIDUtils.getId());//自定义行标识
                items.add(map);
            }
            String id = UUIDUtils.getId();
            List<HashMap<String, Object>> salOrderList = new ArrayList<>();
            HashMap<String, Object> salOrder = new HashMap<>();
            salOrder.put("so_id", jstSalOrderUpload.getKingdeeBillNo());//线上订单号（云星空）
            salOrder.put("shop_id", jstSalOrderUpload.getShopNumber());//店铺编码（云星空）
            salOrder.put("order_date", SqlTool.getNowForString());//日期
            salOrder.put("shop_status", "WAIT_SELLER_SEND_GOODS");//订单状态, WAIT_SELLER_SEND_GOODS——待审核， WAIT_BUYER_PAY——创建, WAIT_BUYER_CONFIRM_GOODS——等待买家确认收货
            salOrder.put("shop_buyer_id", jstSalOrderUpload.getShopBuyerId());//买家帐号（云星空）
            salOrder.put("receiver_address", jstSalOrderUpload.getReceiverAddress());//收货地址（云星空）
            salOrder.put("receiver_name", jstSalOrderUpload.getReceiverName());//收件人（云星空）
            salOrder.put("pay_amount", jstSalOrderUpload.getPayAmount());//应付金额（云星空）
            salOrder.put("freight", jstSalOrderUpload.getFreight());//运费（云星空）
            salOrder.put("receiver_state", jstSalOrderUpload.getReceiverState());//省（云星空）
            salOrder.put("receiver_city", jstSalOrderUpload.getReceiverCity());//市（云星空）
            salOrder.put("receiver_district", jstSalOrderUpload.getReceiverDistrict());//区（云星空）
            salOrder.put("receiver_phone", jstSalOrderUpload.getReceiverPhone());//电话（云星空）
            salOrder.put("receiver_mobile", jstSalOrderUpload.getReceiverMobile());//手机（云星空）
            salOrder.put("logistics_company", jstSalOrderUpload.getLogisticsCompany());//快递公司（云星空）
            salOrder.put("pay", jstSalOrderUpload.getPay());//支付信息（云星空）
            salOrder.put("items", items);//物料信息（云星空）
            salOrderList.add(salOrder);
            //获取accessToken的地址
            String url = ruoYiConfig.getOpenApiUrl() + FormIdEnum.getDBTableName(FormIdEnum.orderUpload.name());
            String result = JuShuiTanUtil.sendOpenApiHttp(url, salOrderList, juShuiTanBlock.getAccessToken());
            AppointMenTinParam appointMenTinParam = JSONObject.parseObject(result, AppointMenTinParam.class);
            if (appointMenTinParam.getCode() == 0){
                SyncLog syncLog = new SyncLog();
                syncLog.setJstBillno(jstSalOrderUpload.getKingdeeBillNo());
                syncLog.setKingdeeBillno(jstSalOrderUpload.getKingdeeBillNo());
                syncLog.setObjectId("0");
                insertSyncLog(syncDto, syncLog, true);
            }else {
                SyncLog syncLog = new SyncLog();
                syncLog.setJstBillno(jstSalOrderUpload.getKingdeeBillNo());
                syncLog.setSyncErrorMsg(appointMenTinParam.getMsg());
                insertSyncLog(syncDto, syncLog, false);
            }
        }
    }

    @Override
    protected void insertSyncLog(SyncDto syncDto, SyncLog syncLog, boolean isSucceed) {
        syncLog.setSyncType("预约入库上传");
        syncLog.setSrcBill("金蝶采购单");
        syncLog.setTarBill("聚水潭预约入库单");
        syncLog.setSyncTime(SqlTool.getNowForString());
        syncLog.setSyncUser(syncDto.getUserName() == null ? "系统自动同步" : syncDto.getUserName());
        if (isSucceed){
            syncLog.setSyncResult("同步成功");
            syncLog.setSyncErrorMsg("无");
        }else {
            syncLog.setIsDispose("未处理");
            syncLog.setSyncResult("同步失败");
        }
        tBxStMapper.insertSyncLog(syncLog);
    }
}
